package com.hundun.login.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hundun.domain.Result;
import com.hundun.domain.Vo.LoginVo;
import com.hundun.login.entity.XcxInfo;
import com.hundun.login.entity.XcxUser;
import com.hundun.login.mapper.XcxUserMapper;
import com.hundun.login.service.XcxInfoService;
import com.hundun.login.service.XcxUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hundun.util.OkHttpUtil;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 谢
 * @since 2020-05-07
 */
@Service
public class XcxUserServiceImpl extends ServiceImpl<XcxUserMapper, XcxUser> implements XcxUserService {

    @Autowired
    XcxInfoService xcxInfoService;

    @Override
    public Result<String> login(XcxUser xcxUser) throws IOException {
        XcxInfo xcxInfo=xcxInfoService.getOne(new QueryWrapper<XcxInfo>().
                eq("app_id",xcxUser.getAppId()));
        String url="https://developer.toutiao.com/api/apps/jscode2session";
        Map<String, Object> map = new HashMap<>(3);
        map.put("appid",xcxUser.getAppId());
        map.put("secret",xcxInfo.getSecret());
        map.put("code",xcxUser.getCode());
        Response response =OkHttpUtil.getInstance().get(map, url);
        assert response.body() != null;
        LoginVo loginVo=JSON.parseObject(response.body().string(), LoginVo.class);
        XcxUser user=getOne(new QueryWrapper<XcxUser>().eq("open_id",loginVo.getOpenid()));
        if(user==null){
            xcxUser.setOpenId(loginVo.getOpenid());
            save(xcxUser);
        }else {
            updateById(xcxUser);
        }
        return Result.OK(loginVo.getOpenid());
    }

}
